import Vue from 'vue'
import Vuex from 'vuex'
import http from './http.js'

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    menu: null
  },
  getters: {
    menu (state) {
      if (state.menu === null) {
        state.menu = JSON.parse(sessionStorage.getItem('menu'))
      }
      return state.menu
    }
  },
  mutations: {
    updateMenu (state, t) {
      state.menu = t
    }
  },
  actions: {
    getMenu ({ getters, commit }) {
      return new Promise((resolve, reject) => {
        console.log(getters)
        if (getters.menu !== null) {
          resolve()
        } else {
          http.get('index/menu')
            .then((result) => {
              commit('updateMenu', result)
              resolve()
            })
        }
      })
    }
  }
})

export default store
